package com.liangdemo.web.upload;


import com.liangdemo.web.model.UploadFile;
import com.liangdemo.web.utils.DateTimeUtil;
import com.liangdemo.web.utils.ErrorCode;
import com.liangdemo.web.utils.GeneralException;
import com.liangdemo.web.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 图片上传工具类
 *
 * @author Mr.Liang
 * @date 2022/5/24 15:18
 */
@Service
@Slf4j
public class UploadUtils {

    private static final String prefix = "/profile";
    //定义一个图片上传路径
    private static final String BASE_PATH = "";
    private static final String SERVER_PATH = "";

    @Value("${customize.upload.path}")
    private String uploadPath;
    @Autowired
    private AttachmentFileService attachmentFileService;


    /**
     * 上传方法
     */

    public static String upload(MultipartFile file) {
        //获得上传文件名称
        String filename = file.getOriginalFilename();
        //使用uuid保证唯一性
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //字符串拼接
        String newFilename = uuid + filename;
        //创建文件实例
        File image = new File(BASE_PATH, newFilename);
        if (image != null) {
            //对文件进行操作
            try {
                file.transferTo(image);
            } catch (IOException e) {
                return null;//如果出现异常返回空
            }
        }
        return SERVER_PATH + newFilename;
    }

    /**
     * 文件上传
     */
    public AttachmentFile uploadManageFile(MultipartFile multipartFile) {
        if (multipartFile == null || StringUtils.isEmpty(multipartFile.getOriginalFilename())) {

        }
        AttachmentFile uploadFile = getUploadDir1(multipartFile);
        if (null == uploadFile) {
            return null;
        }


        File absoluteFile = new File(uploadFile.getPath());
        // File localFile = new File(absoluteFile.getAbsolutePath());
        if (!absoluteFile.getParentFile().exists()) {
            absoluteFile.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(absoluteFile);
        } catch (Exception e) {
            log.error("File transfer error:{}", e.getMessage());
            throw new GeneralException(ErrorCode.ERROR_FILE_TRANSFER);
        }
        String filePath = uploadFile.getPath();
        if (filePath.contains(uploadPath)) {
            filePath = filePath.replace(uploadPath, "");
        }
        filePath = prefix + "/" + filePath;
        uploadFile.setPath(filePath);
        attachmentFileService.save(uploadFile);
        return uploadFile;
    }

    /**
     * 获取上传文件地址
     */
    public UploadFile getUploadDir(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        String fileDir = getDirFilePath();
        File file = new File(fileDir);
        if (!file.exists() && !file.mkdirs()) {
            throw new GeneralException(ErrorCode.ERROR_FOLDER_CREATE);
        }
        UploadFile uploadFile = new UploadFile();
        uploadFile.setName(fileName);
        uploadFile.setPath(fileDir + "/" + getUUIDFileName(fileName));
        uploadFile.setSize(multipartFile.getSize());
        return uploadFile;
    }

    private AttachmentFile getUploadDir1(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        if (org.springframework.util.StringUtils.isEmpty(fileName)) {
            return null;
        }
        // 防止文件过多，按日期生成文件夹
        String fileDir = getDirFilePath();
        File file = new File(fileDir);
        if (!file.exists() && !file.mkdirs()) {
            throw new GeneralException(ErrorCode.ERROR_FOLDER_CREATE);
        }
        AttachmentFile uploadFile = new AttachmentFile();
        uploadFile.setName(fileName);
        uploadFile.setPath(fileDir + "/" + getUUIDFileName(fileName));
        uploadFile.setSize(multipartFile.getSize());
        return uploadFile;
    }

    public String getUUIDFileName(String fileName) {
        return UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 获取文件路径
     *
     * @return
     */
    private String getDirFilePath() {
        String dateDir = uploadPath + DateTimeUtil.nowFormatToYMD();
//        String dateDir = uploadPath + DateTimeUtil.nowFormatToYMD();
        File file = new File(dateDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 判断是否可读、可写
        if (!file.canWrite() || !file.canRead()) {
            log.error("Dir can not read or write：{}", file.getPath());
            throw new GeneralException(ErrorCode.ERROR_FOLDER_READ_OR_WRITE);
        }
        return dateDir;
    }
}
